package com.amber.proyecto.envia.imagenes.sw.usuario;

import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amber.proyecto.envia.imagenes.sw.Principal;
import com.amber.proyecto.envia.imagenes.sw.R;
import com.amber.proyecto.envia.imagenes.sw.utils.ImagenNombreCat;
import com.amber.proyecto.envia.imagenes.sw.utils.ImagenParcelable;
import com.amber.proyecto.envia.imagenes.sw.utils.Variables;

public class MainActivity extends Activity implements OnScrollListener {
	private Bundle bundle;
	private ArrayList<ImagenNombreCat> datos = new ArrayList<ImagenNombreCat>();
    private Cache mCache;

    private ListView mListView;
    private ListAdapter mListAdapter;

    private boolean mIsScrolling;

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listaimagenes);
            
            String ruta = "http://"+Variables.HOST+"/pags/";
            bundle = getIntent().getExtras();
            obtieneImagenesUsuario();

            final int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE))
                            .getMemoryClass();
            final int size = 1024 * 1024 * memClass / 8;

            // Handle orientation change.
            RetainCache c = RetainCache.getOrCreateRetainableCache();
            mCache = c.mRetainedCache;

            if (mCache == null) {
                    // The maximum bitmap pixels allowed in respective direction.
                    // If exceeding, the cache will automatically scale the
                    // bitmaps.
                    final int MAX_PIXELS_WIDTH = 100;
                    final int MAX_PIXELS_HEIGHT = 100;
                    mCache = new Cache(size, MAX_PIXELS_WIDTH, MAX_PIXELS_HEIGHT);
                    c.mRetainedCache = mCache;
            }

            // Initialize the row objects with some random text.
            //final int amountOfItems = sImageUrls.length;
            final int amountOfItems = datos.size();
            mListView = (ListView) findViewById(android.R.id.list);
            ArrayList<Row> objects = new ArrayList<Row>(amountOfItems);

            for (int x = 0; x < amountOfItems; x++) {
                    Row object = new Row();
                    object.mText = datos.get(x).getComentario();
                    object.mBitmapUrl =  ruta+datos.get(x).getNombreImagen();                    
                    /*
                      object.mText = "Hey image number " + Integer.toString(x + 1) + "!";
                      object.mBitmapUrl = sImageUrls[x];
                    */
                    objects.add(object);
            }

            mListAdapter = new ListAdapter(objects);
            mListView.setAdapter(mListAdapter);
            mListView.setOnItemClickListener(mListViewPres);
            mListView.setOnScrollListener(this);
            
            
            Button btnAtras = (Button)findViewById(R.id.btnAtrasAgregaCont);
            btnAtras.setOnClickListener(btnAtrasPres);
            
            Button btnCerrarSesion = (Button)findViewById(R.id.btnCerrarSesionAgregaCont);
            btnCerrarSesion.setOnClickListener(btnCerrarPres);
            
            Button btnInicio = (Button)findViewById(R.id.btnInicioAgregaCont);
            btnInicio.setOnClickListener(btnInicioPres);
            
    }

    private OnItemClickListener mListViewPres = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getBaseContext(), datos.get(position).getNombreImagen(), Toast.LENGTH_LONG).show();
			Intent intent = new Intent();
			
			ImagenParcelable ip = new ImagenParcelable();
        	ip.setNombreImagen(datos.get(position).getNombreImagen());
        	ip.setLatitud(datos.get(position).getLatitud());
        	ip.setLongitud(datos.get(position).getLongitud());
        	ip.setIdCategoria(datos.get(position).getIdCategoria());
        	ip.setComentario(datos.get(position).getComentario());
        	ip.setNombreCategoria(datos.get(position).getNombreCategoria());
        	ip.setCalificacion(datos.get(position).getCalificacion());
        	
    		intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));
			intent.putExtra("datosImagen", ip);
			intent.setClass(MainActivity.this, MuestraInfoUsu.class);
			startActivity(intent);
			finish();
		}
	};
    
    public boolean onCreateOptionsMenu(Menu menu) {

            return true;
    }

    private OnClickListener btnAtrasPres = new OnClickListener() {
		
		public void onClick(View v) {
			Intent intent = new Intent();
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    		intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));
			intent.setClass(MainActivity.this, PrincipalUsuario.class);
			startActivity(intent);
			finish();
		}
	};
	
	private OnClickListener btnCerrarPres = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent();
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    		Variables.inicioSesion = false;
    		intent.setClass(MainActivity.this, Principal.class);
       		startActivity(intent);
    		finish();
		}
	};
	
	private OnClickListener btnInicioPres = new OnClickListener() {

		public void onClick(View v) {
			Intent intent = new Intent();
    		intent.putExtra("correoUsuario", bundle.getString("correoUsuario"));			
    		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    		intent.setClass(MainActivity.this, Principal.class);
       		startActivity(intent);
    		finish();
		}
	};	

    public boolean onOptionsItemSelected(MenuItem menu) {
            // For test purposes only. Clears the cache.
/*
    	if (menu.getItemId() == R.id.menu_settings) {
                    mCache.clear();
                    mListAdapter.notifyDataSetChanged();
            }
            */
            return true;
    }

    private static class ViewHolder {
            private TextView mTextView;
            private ImageView mImageView;

            private ViewHolder(View base) {
                    mTextView = (TextView) base.findViewById(R.id.text);
                    mImageView = (ImageView) base.findViewById(R.id.image);
            }
    }

    private class Row {
            private String mText;
            private String mBitmapUrl;
    }

    public class ListAdapter extends ArrayAdapter<Row> {

            public ListAdapter(ArrayList<Row> objects) {
                    super(MainActivity.this, R.layout.lista_row, objects);
            }

            @Override
            public View getView(final int position, View convertView,
                            ViewGroup parent) {
                    View row = convertView;
                    final ViewHolder holder;

                    if (row == null) {
                            LayoutInflater inflater = getLayoutInflater();
                            row = inflater.inflate(R.layout.lista_row, parent,
                                            false);
                            holder = new ViewHolder(row);
                            row.setTag(holder);
                    } else {
                            holder = (ViewHolder) row.getTag();
                    }

                    final Row rowObject = getItem(position);

                    // Look at the loadBitmap() method description...
                    holder.mTextView.setText(rowObject.mText);
                    mCache.loadBitmap(MainActivity.this, rowObject.mBitmapUrl,
                                    holder.mImageView, mIsScrolling);

                    return row;
            }
    }

    public ListAdapter getAdapter() {
            return mListAdapter;
    }

    public boolean internetIsAvailable() {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                    return true;
            }
            return false;
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (view.getId() == android.R.id.list) {
                    // Set scrolling to true only if the user has flinged the
                    // ListView away, hence we skip downloading a series
                    // of unnecessary bitmaps that the user probably
                    // just want to skip anyways. If we scroll slowly it
                    // will still download bitmaps - that means
                    // that the application won't wait for the user
                    // to lift its finger off the screen in order to
                    // download.
                    if (scrollState == SCROLL_STATE_FLING) {
                            mIsScrolling = true;
                    } else {
                            mIsScrolling = false;
                            mListAdapter.notifyDataSetChanged();
                    }
            }
    }

    public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {


    }
    
    private void obtieneImagenesUsuario(){
		String URL = "http://"+Variables.HOST+"/pags/servicios.php";
		String SOAP_ACTION="capeconnect:servicios:serviciosPortType#buscaImagenesUsuario"; 
		String METHOD_NAME = "buscaImagenesUsuario";
		String NAMESPACE = "http://www.your-company.com/servicios.wsdl";
		
		SoapSerializationEnvelope envelope;
        HttpTransportSE httpt;
      
        try{
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
               
        httpt = new HttpTransportSE(URL);
		request.addProperty("correoUsuario", bundle.getString("correoUsuario"));
        envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11 );
        envelope.dotNet = false;
        envelope.setOutputSoapObject(request);
        httpt.call(SOAP_ACTION, envelope);
        SoapObject result2 =  (SoapObject) envelope.getResponse();

        for(int cont=0; cont< result2.getPropertyCount(); cont ++){
        	SoapObject resultados = (SoapObject) result2.getProperty(cont);
        	//primitivas
        	SoapPrimitive nombreImagen = (SoapPrimitive) resultados.getProperty("nombreImagen");
        	SoapPrimitive latitud = (SoapPrimitive) resultados.getProperty("latitud");
        	SoapPrimitive longitud = (SoapPrimitive) resultados.getProperty("longitud");
        	SoapPrimitive idCategoria = (SoapPrimitive) resultados.getProperty("idCategoria");
        	SoapPrimitive comentario = (SoapPrimitive) resultados.getProperty("comentario");
        	SoapPrimitive nombreCategoria = (SoapPrimitive) resultados.getProperty("nombreCategoria");
            SoapPrimitive calificacion = (SoapPrimitive) resultados.getProperty("calificacion");
        	
        	
        	ImagenNombreCat imagen = new ImagenNombreCat();
        		imagen.setNombreImagen(nombreImagen.toString());
        		imagen.setLatitud(Double.parseDouble(latitud.toString()));
        		imagen.setLongitud(Double.parseDouble(longitud.toString()));
                imagen.setIdCategoria(Integer.parseInt(idCategoria.toString()));
                imagen.setComentario(comentario.toString());
                imagen.setNombreCategoria(nombreCategoria.toString());
                imagen.setCalificacion(Float.parseFloat(calificacion.toString()));
                 datos.add(imagen);
        }
        Log.i("Total ", datos.size()+"");
        
        
        
            
            
        }
        	catch(Exception err){
        		Log.e("Error en llena paises", err.toString());
        	}
	}

}